package cn.qyd.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinWorkerThread;
import java.util.concurrent.RecursiveTask;

/**
 * @author 邱运铎
 * @date 2024-03-26 12:35
 */
public class ForkJoinDemo {
    public static void main(String[] args) {
        int n = 20;
        //为了追踪子线程名称，需要重写ForkJoinWorkerThreadFactory的方法
        final ForkJoinPool.ForkJoinWorkerThreadFactory factory = pool -> {
          final ForkJoinWorkerThread workerThread= ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
          workerThread.setName("My-Thread" + workerThread.getPoolIndex());
          return workerThread;
        };

        //创建分治任务线程池，可以追踪到线程名称
        ForkJoinPool forkJoinPool = new ForkJoinPool(4, factory,null,false);

        //快速创建分治任务线程池
//        ForkJoinPool forkJoinPool1 = new ForkJoinPool(4);

        //创建分治任务

        Fibonacci fibonacci = new Fibonacci(n);

        Integer invoke = forkJoinPool.invoke(fibonacci);
        System.out.println("Fibonacci " + n + " 的结果是： " + invoke);

    }
    //定义拆分任务,写好拆分逻辑
    static class Fibonacci extends RecursiveTask<Integer> {
        private int num;

        private Fibonacci(int n) {
            this.num = n;
        }

        @Override
        public Integer compute() {
            if ( num <= 1) {
                return num;
            }
            Fibonacci f1 = new Fibonacci(num - 1);

            //拆分子任务
            f1.fork();
            Fibonacci f2 = new Fibonacci(num - 2);
            return  f2.compute() + f1.join();
        }
    }
}
